package cn.cs.controller;

import cn.cs.client.RestClientUserClient;
import cn.cs.common.*;
import cn.cs.config.WXPayConfig;
import cn.cs.pojo.ClientUser;
import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * 微信登录控制器
 *
 * @author yuexl
 */
@Controller
@RequestMapping(value = "/vendor")
public class WxUserInfoController {
    private Logger logger = Logger.getLogger(WxPaymentController.class);
    @Resource
    private RestClientUserClient clientUserClient;

    @Resource
    private TokenUtils tokenUtils;
    @Resource
    private WXPayConfig wxPayConfig;

    @Resource
    private LogUtils logUtils;

    /**
     * 微信登录——第一步：获取code
     * 注意每个用户只用授权一次，不用重复授权，授权之后就可以获取相关的用户信息
     *
     * @param response
     */
    @RequestMapping(value = "/p/wechat/login")
    public void wechatLogin(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String key = request.getParameter("key");
        String userId = request.getParameter("userId");
        boolean isTrue = false;
        if (EmptyUtils.isNotEmpty(userId)) {
            ClientUser user = clientUserClient.getClientUserById(userId);
            if (user != null) {
                String accessToken = user.getAccessToken();
                String tokenLoseTime = user.getTokenLoseTime();

                if (EmptyUtils.isNotEmpty(accessToken) && EmptyUtils.isNotEmpty(tokenLoseTime)) {
                    long lostTime = Long.valueOf(tokenLoseTime);
                    long time = System.currentTimeMillis();
                    if (lostTime > time) {
                        String token = tokenUtils.generateToken("unknown", user);
                        tokenUtils.save(token, user);
                        StringBuilder loginPage = new StringBuilder();
                        loginPage.append("http://www.zzzsyh.com/index.html#/authorization");
                        loginPage.append("?token=" + token);
                        loginPage.append("&openid=" + user.getOpenId());
                        loginPage.append("&key=" + key);
                        try {
                            response.sendRedirect(loginPage.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                            isTrue = true;
                        }
                    } else {
                        isTrue = true;
                    }
                } else {
                    isTrue = true;
                }
            } else {
                isTrue = true;
            }
        } else {
            isTrue = true;
        }
        if (isTrue) {
            String url = wxPayConfig.getRedirectUri() + "%3fkey%3d" + key;
            String qrconnect = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxPayConfig.getAppID() + "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            logger.info("info---------------------------------------------------------qrconnect:" + qrconnect);
            try {
                response.sendRedirect(qrconnect);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 微信登录——第二步：通过code换取access_token
     *
     * @param code
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/p/wechat/callback")
    public void wechatCallback(@RequestParam String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String key = request.getParameter("key");
        System.out.println(key + "------------------------------------------");
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxPayConfig.getAppID() + "&secret=" + wxPayConfig.getAppSecret() + "&code=" +
                code + "&grant_type=authorization_code";
        logger.info("info---------------------------------------------------------accessTokenUrl:" + accessTokenUrl);
        response.setContentType("text/html;charset=utf-8");
        String json = UrlUtils.loadURL(accessTokenUrl);
        logger.info("info---------------------------------------------------------json:" + json);
        System.out.println("json:" + json);
        Map<String, Object> wechatToken = JSON.parseObject(json, Map.class);
        System.out.println("wechatToken-----------------------------------" + wechatToken);
        System.out.println("openid-----------------------------------" + wechatToken.get("openid").toString());
        System.out.println("access_token-----------------------------------" + wechatToken.get("access_token").toString());
        //验证数据库是否存在该用户
        ClientUser user = clientUserClient.getClientUserByOpenId(wechatToken.get("openid").toString());
        if (user == null) {//如果不存在则添加用户
            user = new ClientUser();
            user.setOpenId(wechatToken.get("openid").toString());
            String id = IdWorker.getId();
            user.setId(id);
            clientUserClient.insertClientUser(user);
        } else {
            ClientUser clientUser = new ClientUser();
            //更新accessToken
            clientUser.setAccessToken(wechatToken.get("access_token").toString());
            long tokenTime = Long.valueOf(wechatToken.get("expires_in").toString());
            long time = System.currentTimeMillis();
            time = time + tokenTime * 1000;
            clientUser.setTokenLoseTime(String.valueOf(time));
            clientUser.setOpenId(wechatToken.get("openid").toString());
            clientUserClient.updateClientUserByOpenId(clientUser);
        }

        String token = tokenUtils.generateToken("unknown", user);
        tokenUtils.save(token, user);
        //返回前端处理
        StringBuilder loginPage = new StringBuilder();
        loginPage.append("http://www.zzzsyh.com/index.html#/authorization");
        loginPage.append("?token=" + token);
//            loginPage.append("&access_token=" + wechatToken.get("access_token").toString());
//            loginPage.append("&expires_in=" + wechatToken.get("expires_in").toString());
//            loginPage.append("&refresh_token=" + wechatToken.get("refresh_token").toString());
        loginPage.append("&openid=" + wechatToken.get("openid").toString());
        loginPage.append("&key=" + key);

        System.out.println(loginPage.toString());
        response.sendRedirect(loginPage.toString());


    }

    @RequestMapping(value = "/p/wechat/aaa")
    @ResponseBody
    public Dto wechatCallback(String name) throws Exception {
        ClientUser user = new ClientUser();
        user.setId("1");
        user.setUserName(name);
        clientUserClient.updateClientUser(user);
        return DtoUtil.returnSuccess("", user);
    }

    /**
     * 获取微信用户信息
     *
     * @param openid 微信用户唯一标识
     * @return
     */
    @RequestMapping(value = "/p/wechat/user/info", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    Dto wechatUserInfo(@RequestParam String openid) {
        try {
            ClientUser user = clientUserClient.getClientUserByOpenId(openid);

            if (user != null) {
                String accessToken = user.getAccessToken();
                String tokenLoseTime = user.getTokenLoseTime();

                if (EmptyUtils.isNotEmpty(accessToken) && EmptyUtils.isNotEmpty(tokenLoseTime)) {
                    long lostTime = Long.valueOf(tokenLoseTime);
                    long time = System.currentTimeMillis();
                    if (lostTime > time) {
                        //加载用户信息
                        String userInfoJson = sendPost("https://api.weixin.qq.com/sns/userinfo?access_token="
                                + accessToken
                                + "&openid=" + openid, ""
                        );
                        Map<String, Object> userInfo = JSON.parseObject(userInfoJson, Map.class);
                        logUtils.i("cs_pay", userInfoJson);
                        ClientUser clientUser = new ClientUser();
                        clientUser.setUserName(userInfo.get("nickname").toString());
                        clientUser.setHeadimg(userInfo.get("headimgurl").toString());
                        clientUser.setOpenId(openid);
                        clientUserClient.updateClientUsersByOpenId(clientUser);

                        return DtoUtil.returnDataSuccess(userInfo);
                    } else {
                        return DtoUtil.returnFail("AccessToken超时，请重新获取", "002");
                    }
                } else {
                    return DtoUtil.returnFail("用户AccessToken为空，请重新授权", "003");
                }
            } else {
                return DtoUtil.returnFail("用户不存在，请授权后获取", "002");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), "授权失败");
        }
    }


    public static String sendPost(String url, String param) throws Exception {
        Logger logger = Logger.getLogger(WxPaymentController.class);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数

            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        logger.debug("---------------------------------------------------------result微信昵称:" + result);
        return result;

        }

    @RequestMapping(value = "/aaaaa")
    @ResponseBody
        public Dto main (){
            logUtils.i("cs_pay", "123");
        logger.debug("---------------------------------------------------------json:" + 123);
        logger.info("---------------------------------------------------------json:" + 123);
            return DtoUtil.returnSuccess();
        }

    }

